package com.verisette.ncos.service.master.bizunit;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.service.bizunit.CommonBusinessUnit;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.dao.AccessControlDAO;
import com.verisette.ncos.persistence.domain.LogUserAccess;
import com.verisette.ncos.persistence.domain.MasterUserGroupToUserProfile;

public class UserAccessLogBU extends CommonBusinessUnit {
	private Logger logger = Logger.getLogger(UserAccessLogBU.class);
	
	private AccessControlDAO accessControlDAO;	
	@Required
	@Autowired
	public void setAccessControlDAO(AccessControlDAO accessControlDAO) {
		this.accessControlDAO = accessControlDAO;
	}
	
	public void execute(ProcessContext processContext) throws ProcessException {
		Map<String, Object> inputMap = (Map<String, Object>)processContext.getValueObject();
		
		UserBean masUser = (UserBean) inputMap.get(ProjectConstant.USER_PROFILE);
		String ipAddress = (String)inputMap.get(ProjectConstant.USER_PROFILE_IP_ADDRESS);
		
		List<MasterUserGroupToUserProfile> masterUserGroupToUserProfileList = accessControlDAO.listUser(masUser.getUsername(), masUser.getRole());
		if (masterUserGroupToUserProfileList.size() > 0) {
			MasterUserGroupToUserProfile o = masterUserGroupToUserProfileList.get(0);
			LogUserAccess logUserAccess = new LogUserAccess();
			//logUserAccess.setUsgId(o.getUsgId());	//Comment by thippawan @20101004 :- change database field
			logUserAccess.setUspId(o.getUspId());
			logUserAccess.setUacDatetime(new Timestamp(new Date().getTime()));
			logUserAccess.setUacIpAddr(ipAddress);
			commonDAO.save(logUserAccess);
		} else {
			logger.warn("Can't find User Id and User Group Id. (USERNAME = "+ masUser.getUsername() +" USERGROUP = "+ masUser.getRole() + ")" );
		}
	}

}
